<template>
  <div>
    <!-- 添加商品组件 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>添加商品</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card>
      <el-alert title="添加商品信息" type="info" show-icon center :closable="false"></el-alert>
      <!-- 步骤条 -->
      <el-steps :space="200" align-center :active="activeIndex -0" finish-status="success">
        <el-step title="基本信息"></el-step>
        <el-step title="商品参数"></el-step>
        <el-step title="商品属性"></el-step>
        <el-step title="商品图片"></el-step>
        <el-step title="商品内容"></el-step>
        <el-step title="完成"></el-step>
      </el-steps>
      <!-- tabs栏竖行 -->
      <!-- v-model绑定的是字符串0，而el-steps里面默认的是数字，需要把字符串转换为数字 -->
      <el-form
        :model="addGoodsForm"
        :rules="addGoodsRules"
        ref="addGoodsRef"
        label-width="top"
        class="demo-ruleForm"
      >
        <el-tabs
          :tab-position="'left'"
          v-model="activeIndex"
          :before-leave="beforeTabLeave"
          @tab-click="TabsClicked"
        >
          <el-tab-pane label="基本信息" name="0">
            <!-- 1,基本信息表单 type=number规定只能输入数字 -->

            <el-form-item label="商品名称" prop="goods_name">
              <el-input v-model="addGoodsForm.goods_name"></el-input>
            </el-form-item>
            <el-form-item label="商品价格" prop="goods_price">
              <el-input v-model="addGoodsForm.goods_price" type="number"></el-input>
            </el-form-item>
            <el-form-item label="商品重量" prop="goods_weight">
              <el-input v-model="addGoodsForm.goods_weight" type="number"></el-input>
            </el-form-item>
            <el-form-item label="商品数量" prop="goods_number">
              <el-input v-model="addGoodsForm.goods_number" type="number"></el-input>
            </el-form-item>
            <el-form-item label="商品分类" prop="goods_cat">
              <!-- 级联选择器获取商品分类 -->
              <!-- options分类列表  props绑定对象 -->
              <br />
              <el-cascader
                v-model="addGoodsForm.goods_cat"
                :options="cateList"
                expandTrigger="hover"
                :props="addGoodsProps"
                @change="handleChange"
                style="width:100%"
              ></el-cascader>
              <!-- <el-input></el-input> -->
            </el-form-item>
            <el-form-item label="商品属性">
              <el-input></el-input>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品参数" name="1">
            <!-- 渲染表单的item项  商品分类 -->
            <el-form-item
              v-for="item in this.manyTabData"
              :key="item.attr_id"
              :label="item.attr_name"
            >
              <br />
              <!-- 复选框组 双重循环，渲染当前分类的属性 -->
              <el-checkbox-group v-model="item.attr_vals">
                <el-checkbox :label="cb" v-for="(cb,i) in item.attr_vals" :key="i" border></el-checkbox>
              </el-checkbox-group>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品属性" name="2">
            <el-form-item
              v-for="item in this.onlyTabData"
              :key="item.attr_id"
              :label="item.attr_name"
            >
              <el-input v-model="item.attr_vals"></el-input>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品图片" name="3">
            <!-- 因为upload在图片进行上传的时候不是使用的axios发送请求，需要为上传图片的请求添加token，即为upload组件添加headers属性 -->
            <!-- action指定图片上传的api接口 on-preview当点击图片时触发事件进行预览操作，处理图片预览 on-success在用户上传图片成功的时候触发 list-type预览图片的方式 headers设置上传图片的请求头 -->
            <el-upload
              :action="uploadUrl"
              :on-preview="handlePreview"
              :on-success="handleSuccess"
              :on-remove="handleRemove"
              list-type="picture"
              :headers="headerObj"
            >
              <el-button size="small" type="primary">点击上传</el-button>
              <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
            </el-upload>
          </el-tab-pane>
          <el-tab-pane label="商品内容" name="4">
            <quill-editor v-model="addGoodsForm.goods_introduce"></quill-editor>
            <el-button type="primary" class="btn" @click="AddGoodsBtn">确认</el-button>
          </el-tab-pane>
        </el-tabs>
      </el-form>
    </el-card>
    <!-- 图片预览dialog框 -->
    <el-dialog title="图片预览" :visible.sync="previewVisible" width="50%">
      <img :src="this.previewPath" class="previewImg" />
    </el-dialog>
  </div>
</template>
<script>
import _ from 'lodash'
export default {
  data() {
    return {
      activeIndex: '0',
      addGoodsForm: {
        goods_name: '',
        goods_price: 0,
        goods_weight: 0,
        goods_number: 0,
        goods_cat: [],
        pics: [],
        goods_introduce: ''
      },
      addGoodsRules: {
        goods_name: [
          { required: true, message: '请输入商品名称', trigger: 'blur' },
          { min: 2, max: 30, message: '长度在 2 到 30 个字符', trigger: 'blur' }
        ],
        goods_price: [
          { required: true, message: '请输入商品价格', trigger: 'blur' }
        ],
        goods_weight: [
          { required: true, message: '请输入商品重量', trigger: 'blur' }
        ],
        goods_number: [
          { required: true, message: '请输入商品数量', trigger: 'blur' }
        ]
      },
      cateList: [],
      addGoodsProps: {
        value: 'cat_id',
        label: 'cat_name',
        children: 'children'
      },
      // 动态参数
      manyTabData: [],
      // 静态参数
      onlyTabData: [],
      uploadUrl: 'http://127.0.0.1:8888/api/private/v1/upload',
      // 图片上传的请求头
      headerObj: { Authorization: window.sessionStorage.getItem('token') },
      // 保存预览图片的url地址
      previewPath: '',
      // 控制预览图片对话框的显示和隐藏
      previewVisible: false
      // 上传图像的临时路径
    }
  },
  created() {
    this.getCateList()
  },
  computed: {
    cateId() {
      if (this.addGoodsForm.goods_cat.length === 3) {
        return this.addGoodsForm.goods_cat[2]
      }
      return null
    }
  },
  methods: {
    // 获取商品分类
    async getCateList() {
      const { data: res } = await this.$http.get('categories')
      if (res.meta.status !== 200) {
        return this.$message.error('获取商品分类数据失败')
      }
      console.log(res)
      this.cateList = res.data
    },
    handleChange() {
      if (this.addGoodsForm.goods_cat.length !== 3) {
        this.addGoodsForm.goods_cat = []
        this.$message.info('请选择三级商品分类')
      }
    },
    // tabs准备切换触发的事件函数
    beforeTabLeave(activeName, oldActiveName) {
      // console.log(
      //   '即将要去的索引' + activeName,
      //   '即将离开的索引' + oldActiveName
      // )
      if (oldActiveName === '0') {
        if (this.addGoodsForm.goods_cat.length !== 3) {
          this.$message.error('请选择商品分类')
          //  不允许向下跳转
          return false
        } else if (this.addGoodsForm.goods_name.trim() === '') {
          this.$message.error('请选择商品名称')
          return false
        } else if (this.addGoodsForm.goods_price === '0') {
          this.$message.error('请选择商品价格')
          return false
        } else if (this.addGoodsForm.goods_weight === '0') {
          this.$message.error('请选择商品重量')
          return false
        } else if (this.addGoodsForm.goods_number === '0') {
          this.$message.error('请选择商品数量')
          return false
        }
      }
    },
    // tab切换时获取参数,当点击索引为1的
    async TabsClicked() {
      if (this.activeIndex === '1') {
        const { data: res } = await this.$http.get(
          `categories/${this.cateId}/attributes`,
          {
            params: { sel: 'many' }
          }
        )
        if (res.meta.status !== 200) {
          return this.$message.error(res.meta.msg)
        }
        res.data.forEach(item => {
          item.attr_vals =
            item.attr_vals.length === 0 ? [] : item.attr_vals.split(' ')
        })
        this.manyTabData = res.data
        console.log(res.data)
      } else if (this.activeIndex === '2') {
        const { data: res } = await this.$http.get(
          `categories/${this.cateId}/attributes`,
          {
            params: { sel: 'only' }
          }
        )
        if (res.meta.status !== 200) {
          return this.$message.error(res.meta.msg)
        }
        this.onlyTabData = res.data
        console.log(res.data)
      }
    },
    handlePreview(file) {
      this.previewPath = file.response.data.url
      this.previewVisible = true
    },
    // 文件上传成功保存到表单中，钩子函数
    handleSuccess(response) {
      // 拼接得到一个图片信息的对象
      const picInfo = { pic: response.data.tmp_path }
      // 将图片的信息对象添加到到addGoodsFrom
      this.addGoodsForm.pics.push(picInfo)
      console.log(this.addGoodsForm)
    },
    handleRemove(file) {
      console.log(file)
      // 获取将要删除的图片的临时路径
      const fileInfo = file.response.data.tmp_path
      // 从pics数组中找到这个图片对应的索引值
      const i = this.addGoodsForm.pics.findIndex(item => item.pic === fileInfo)
      // 调用splice方法，把图片信息从pics从数组中移除
      this.addGoodsForm.pics.splice(i, 1)
    },
    // 添加商品
    AddGoodsBtn() {
      this.$refs.addGoodsRef.validate(async valid => {
        // console.log(valid)
        if (!valid) {
          return this.$message.error('请填写必要的表单项')
        }
        // 对静态属性和动态参数进行处理，级联选择器里面的参数是数组，发送请求的时候参数却是字符串，但是不能用join(' ')的用法，因为数据是响应式的，这个时候就要用深拷贝重新拷贝一份地址，
        // 将addGoodsFrom重新拷贝一份，避免goods_cat数组转换为字符串导致级联选择器出错
        // 深拷贝
        const form = _.cloneDeep(this.addGoodsForm)
        // 将数组转换成字符串
        form.goods_cat = form.goods_cat.join(',')
        // 处理attrs数组
        // 处理manyData里的数据
        form.attrs = []
        this.manyTabData.forEach(item => {
          form.attrs.push({
            attr_id: item.attr_id,
            attr_value: item.attr_vals.join(' ')
          })
        })
        console.log(this.manyTabData)
        console.log(form)

        // 处理onlyData里的数据
        this.onlyTabData.forEach(item => {
          form.attrs.push({
            attr_id: item.attr_id,
            attr_value: item.attr_vals
          })
        })
        console.log(form)

        const { data: res } = await this.$http.post('goods', form)
        if (res.meta.status !== 201) {
          return this.$message.error('添加失败')
        }
        this.$message.success('添加成功')
        this.$router.push('/goods')
        console.log(res)
      })
    }
  }
}
</script>
<style lang="less" scoped>
.el-checkbox {
  margin-right: 10px !important;
}
.previewImg {
  width: 100%;
}
.btn {
  margin-top: 10px;
}
</style>
